﻿
$(document).ready(
    function () {
        $.ajax({
            url: 'http://' + document.location.host + '/TwitterBobbyService.svc/GetAllChannels',
            async: false,
            dataType: 'json',
            success: function (data) {
                for (i in data) {
                    $('#channelslist').append('<li><div>' + data[i].ChannelName + '</div></li>');
                }
                $('#channelslist li:first div').addClass('selected');
            }
        });

        $('#channelslist li div').click(function () {
            $('.selected').removeClass('selected');
            $(this).addClass('selected');
            var channelname = $('.selected').html();
            $('#chatcontent').html('');
            $.ajax({
                url: 'http://localhost:37769/TwitterBobbyService.svc/GetMessagesByChannelName/' + channelname,
                async: false,
                dataType: 'json',
                success: function (data) {
                    for (i in data) {
                        var date = new Date(parseInt(data[i].MessageDate.substr(6)));
                        $('#chatcontent').append('<p>' + date.getHours() + ':' + date.getMinutes()
                    + ':' + date.getSeconds() + ':'
                     + ' - ' + data[i].Text + '</p>');
                    }
                }
            });
        });

        $('#postbutton').click(function () {
            var m = new Object();
            var text = $('#posttextfield').val();
            m.MsgText = text;
            m.MsgDate = new Date();
            m.MsgChannel = $('.selected').html();

            var dataToSend = '{"msg":' + JSON.stringify(m) + '}';
            alert(dataToSend);
            
            $.ajax({
                type: "POST",
                url: "http: //localhost:37769/TwitterBobbyService.svc/Post",
                data: dataToSend,
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (response) {
                }
            });

            $('#posttextfield').val('');
        });

        

    }
);